package com.springboot.util.threadpool;

import com.springboot.util.config.SystemProperties;
import com.springboot.util.spring.SpringUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @description:
 * EnableAsync 启用异步任务
 * @author: zyj
 * @create: 2020-09-29 14:51
 **/
@Configuration
public class TaskPoolConfig {

    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        SystemProperties systemProperties = SpringUtil.getBean(SystemProperties.class);

        //配置核心线程数
        taskExecutor.setCorePoolSize(systemProperties.getCorePoolSize());
        //配置最大线程数
        taskExecutor.setMaxPoolSize(systemProperties.getMaxPoolSize());
        //配置队列大小
        taskExecutor.setQueueCapacity(systemProperties.getQueueCapacity());
        //线程活跃时间（秒）
        taskExecutor.setKeepAliveSeconds(systemProperties.getKeepAliveSeconds());
        //线程的名称前缀
        taskExecutor.setThreadNamePrefix(systemProperties.getNamePrefix());
        //等待所有任务结束后再关闭线程池
        taskExecutor.setWaitForTasksToCompleteOnShutdown(systemProperties.isWaitForTasksToCompleteOnShutdown());
        //设置拒绝策略
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待的时间
        taskExecutor.setAwaitTerminationSeconds(60);

        return taskExecutor;
    }


}
